package com.cuicuisha.gxyp.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.cuicuisha.gxyp.common.exception.CustomException;
import com.cuicuisha.gxyp.manager.mapper.SysUserMapper;
import com.cuicuisha.gxyp.manager.service.SysUserService;
import com.cuicuisha.gxyp.model.dto.system.LoginDto;
import com.cuicuisha.gxyp.model.dto.system.SysRoleDto;
import com.cuicuisha.gxyp.model.dto.system.SysUserDto;
import com.cuicuisha.gxyp.model.entity.system.SysUser;
import com.cuicuisha.gxyp.model.entity.system.SysUserAuthContextUtil;
import com.cuicuisha.gxyp.model.vo.common.ResultCodeEnum;
import com.cuicuisha.gxyp.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: SysUserServiceImpl
 * Description:
 *
 * @Author 脆脆鲨
 * @Create 2024-09-09 20:37
 * @Version 1.0
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 根据用户名查询用户数据
     *
     * @param loginDto
     * @return
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);

        if(sysUser == null){
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(sysUser.getPassword())){
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }

        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)){
            throw new CustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        // Object:ID:Field
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser),30, TimeUnit.MINUTES);
        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey) ;
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token) ;
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> userPageInfo = new PageInfo<>(sysUserList);
        return userPageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        // 根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.findByUserName(sysUser.getUserName()) ;
        if(dbSysUser != null) {
            throw new CustomException(ResultCodeEnum.USER_NAME_IS_EXISTS) ;
        }

        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        sysUserMapper.saveSysUser(sysUser) ;
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }


}
